package com.youbenzi.servlet;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class DeployServlet extends HttpServlet {

	private static final long serialVersionUID = 1670480692259614261L;
	public static final String USER_AGENT_KEY = "User-Agent";
	public static final String USER_AGENT_VALUE = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36";
	private static String PROJECT_PACKAGE_NAME = "";
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String fileUrl = req.getParameter("targetFile");
		if(fileUrl == null) {
			resp.setContentType("text/html");
			resp.getWriter().print("Gitee ci delpoy project.<br/><a href=\"http://git.oschina.net/cevin15/gitee-ci-deploy\">Learn more.</a>");
			return;
		}
		System.out.println("请求到达");
		System.out.println(fileUrl);
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println("开始下载～");

				downloadFile(fileUrl, "./" + PROJECT_PACKAGE_NAME);
				System.out.println("项目包下载完成，开始部署～");
				deploy();
				System.out.println("部署完成");
			}
		}).start();
	}

	private static void downloadFile(String url, String path) {
		try (CloseableHttpClient httpclient = HttpClients.createDefault();) {
			HttpGet httpGet = new HttpGet(url);
			httpGet.addHeader(USER_AGENT_KEY, USER_AGENT_VALUE);
			CloseableHttpResponse response = httpclient.execute(httpGet);
			try {
				int status = response.getStatusLine().getStatusCode();
				if (status == 200) {
					HttpEntity entity = response.getEntity();
					InputStream is = entity.getContent();
					ByteArrayOutputStream outputStream = inputStream2ByteArrayOutputStream(is);
					File target = new File(path);
					FileUtils.writeByteArrayToFile(target, outputStream.toByteArray());
					EntityUtils.consume(entity);
				}
			} finally {
				response.close();
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void deploy() {
		String[] cmds = { "sh", "./invoke.sh" };
		ProcessBuilder pb = new ProcessBuilder(cmds);
		pb.redirectErrorStream(true);
		try {
			Process p = pb.start();
			try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));) {
				String line = null;
				while ((line = br.readLine()) != null) {
					System.out.println("\t" + line);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static ByteArrayOutputStream inputStream2ByteArrayOutputStream(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		while ((len = is.read(buffer)) > -1) {
			baos.write(buffer, 0, len);
		}
		baos.flush();
		return baos;
	}

	public static void main(String[] args) throws Exception {
		int port = Integer.parseInt(args[0]);
		PROJECT_PACKAGE_NAME = args[1];
		
		Server server = new Server(port);
		ServletContextHandler contextHandler = new ServletContextHandler();
		contextHandler.addServlet(new ServletHolder(DeployServlet.class), "/deploy");
	      
	    server.setHandler(contextHandler); 
	    server.start();
	}
}
